import {Component, OnInit} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {BLOCK_URL} from '../../config';
import {ActivatedRoute} from '@angular/router';

export interface Block {
  hash: string;
  timestamp: string;
  index: number;
  data: string;
  previousHash: string;
  nonce: number;
  difficulty: string;
}


@Component({
  selector: 'app-find-block',
  templateUrl: './find-block.component.html',
  styleUrls: ['./find-block.component.css']
})
export class FindBlockComponent implements OnInit {
  blockHash: string;
  showInput: any = true;
  index: number;
  previousHash: string;
  hash: string;
  nonce: number;
  timestamp: string;
  difficulty: string;
  content: string;

  constructor(private http: HttpClient, private route: ActivatedRoute) {
    this.route.queryParams.subscribe(params => {
      this.blockHash = params['hash'];
      this.loadData();
      this.showInput = true;
    });
  }

  ngOnInit() {
  }

  loadData() {
    this.http.post<Block>(BLOCK_URL + 'getBlock', {'hash': this.blockHash}).subscribe(data => {
      console.log(data);
      this.showInput = false;
      this.index = data.index;
      this.previousHash = data.previousHash;
      this.nonce = data.nonce;
      this.timestamp = data.timestamp;
      this.content = JSON.stringify(data.data);
      this.difficulty = data.difficulty;
    });
  }

  submit() {
    if (this.blockHash) {
      this.loadData();
    }
  }

}
